package com.java.springcloud.service;

import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dushougudu
 */
@Service
public class MongoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public String send(Integer count) {
        List<Document> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            Document document = new Document();
            document.put("name", "同学" + i);
            document.put("score", i);
            list.add(document);
        }
        mongoTemplate.getCollection("student").insertMany(list);
        return "success";
    }

    @Transactional(rollbackFor = Exception.class)
    public String sendFail(Integer count) throws Exception {
        for (int i = 1; i <= count; i++) {
            Document document = new Document();
            document.put("name", "学生" + i);
            document.put("score", i);
            if (i >= 5) {
                throw new Exception("异常了");
            }
            mongoTemplate.getCollection("student").insertOne(document);
        }
        return "success";
    }

    @Transactional(rollbackFor = Exception.class)
    public String sendFailMulti(Integer count) throws Exception {
        for (int i = 1; i <= count; i++) {
            Document document = new Document();
            document.put("name", "学生" + i);
            document.put("score", i);
            mongoTemplate.getCollection("student").insertOne(document);
        }

        for (int i = 1; i <= count; i++) {
            Document document = new Document();
            document.put("name", "老师" + i);
            document.put("score", i);
            if (i >= 5) {
                throw new Exception("异常了");
            }
            mongoTemplate.getCollection("teacher").insertOne(document);
        }
        return "success";
    }
}
